// @Author chenyong 2023/2/27 12:25:00
package mindMap

import (
	"archive/zip"
	"encoding/json"
	"io"
	"log"
)

const (
	contentFilename = "content.json"
)

type MindMapFile struct {
	FilePath string  `json:"filePath"`
	Sheet    []Sheet `json:"sheet"`
}

func (f MindMapFile) ReadmindMapFileData() RootTopic {
	zipFp, zipErr := zip.OpenReader(f.FilePath)
	if zipErr != nil {
		log.Fatalf("Failed to open zip file %s: %s\n", f.FilePath, zipErr)
	}
	for _, file := range zipFp.File {
		if file.FileInfo().Name() != contentFilename {
			continue
		}

		contentFp, openErr := file.Open()
		if openErr != nil {
			log.Fatalf("Failed to open file %s: %s\n", contentFilename, openErr)
		}

		contentByte, readErr := io.ReadAll(contentFp)
		if readErr != nil {
			log.Fatalf("Failed to read file %s: %s\n", contentFilename, readErr)
		}

		jsonErr := json.Unmarshal(contentByte, &f.Sheet)
		if jsonErr != nil {
			log.Fatalf("Failed to parse json to Sheet: %s\n", jsonErr)
		}
	}

	return f.Sheet[0].RootTopic
}
